package org.example.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.example.enums.BizCodeEnum;
import org.example.enums.EventMessageTypeEnum;
import org.example.exception.BizException;
import org.example.model.EventMessage;
import org.example.service.ShortLinkService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @description: mq消费者
 * @author: 谢超
 * @date: 2023/8/24 9:58
 */
@Component
@Slf4j
//@RabbitListener(queues = "short_link.del.mapping.queue")
@RabbitListener(queuesToDeclare = {@Queue("short_link.del.mapping.queue")}) // 这种可以用于MQ中若无对应名称的队列/交换机的时候用，它自动创建队列
public class ShortLinkDelMappingMqListener {

    @Resource
    private ShortLinkService shortLinkService;

    @RabbitHandler
    public void shortLinkHandler(EventMessage eventMessage, Message message, Channel channel) throws IOException {
        log.info("监听到ShortLinkDelMappingMQListener 消息内容:{}", message);
        try {
            // 修改eventMessage关于type类型
            eventMessage.setEventMessageType(EventMessageTypeEnum.SHORT_LINK_DEL_MAPPING.name());
            // 关于添加短链的处理逻辑
            shortLinkService.handlerDelShortLink(eventMessage);
        } catch (Exception e) {
            // 消费失败，处理异常，还有进行其他操作，比如记录其他原因
            log.error("消费失败Mapping：{}", eventMessage);
            log.error("失败",e);
            throw new BizException(BizCodeEnum.MQ_CONSUME_EXCEPTION);
        }

        log.info("消费成功mapping: {}", eventMessage);

        // 手动+确认消息消费成功
        // channel.basicAck(tag, false);
    }
}
